package com.czmh.etc.onlinepubsys.services.mingchuang.impl;

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.czmh.etc.onlinepubsys.entity.mingchuang.*;
import com.czmh.etc.onlinepubsys.maper.EtcOrderMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.*;
import com.czmh.etc.onlinepubsys.model.EtcDevice;
import com.czmh.etc.onlinepubsys.model.SysConfig;
import com.czmh.etc.onlinepubsys.services.SysConfigService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IDeviceService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IObuService;
import com.czmh.etc.onlinepubsys.utils.HttpUtils;
import com.czmh.etc.onlinepubsys.utils.PayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ObuServiceImpl implements IObuService {
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private ApplyInfoMapper applyInfoMapper;

    @Autowired
    private CurrentContextMapper currentContextMapper;

    @Autowired
    private MingChuangEtcObuMapper mingChuangEtcObuMapper;

    @Autowired
    private MingchuangOrderMapper mingchuangOrderMapper;

    @Autowired
    private EtcDealerObuMapper etcDealerObuMapper;

    @Autowired
    private EtcOrderMapper etcOrderMapper;


    @Override
    public void cmgActiveComplete(String obuId, String userId) {
        QueryWrapper<CurrentContext> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.gt("state", 0);
        qw.eq("delete_flag", 0);
        qw.eq("pay_mode", 1);
        CurrentContext ctx = currentContextMapper.selectOne(qw);

        ApplyInfo applyInfo = applyInfoMapper.selectById(ctx.getApplyId());

        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo", ctx.getOrderNo());
        EtcOrder etcOrder = mingchuangOrderMapper.selectOne(wrapper);


        Integer activeState = 1;
        applyInfo.setState(2); //更改申请的状态为设备已激活
        applyInfoMapper.updateById(applyInfo);

        //删除当前进行时-逻辑删除
        ctx.setDeleteFlag(1);
        currentContextMapper.updateById(ctx);
        //currentContextMapper.deleteById(ctx.getId());

        //推送激活数据给到第三方
        try {
            String thirdCustomId = "651682741070467072";
            SysConfig cyCustomConfig = sysConfigService.queryByKey("cy_custom_config");
            if (cyCustomConfig != null && cyCustomConfig.getConfigValue() != null && org.apache.commons.lang3.StringUtils.isNotEmpty(cyCustomConfig.getConfigValue())) {
                String thirdCustom = cyCustomConfig.getConfigValue();
                JSONObject object = JSON.parseObject(thirdCustom);
                //if (ctx.getChannel() != null && ctx.getChannel().equalsIgnoreCase(object.getString("customId"))) {
                    //同步消息给第三方充值系统（好司机）
                    JSONObject obj = new JSONObject();
                    obj.put("vehiclePlate", etcOrder.getVehPlate());
                    obj.put("phone", DesensitizedUtil.desensitized(etcOrder.getPhone(), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
                    Map<String, String> m = new HashMap<>();
                    m.put("remark", obj.toJSONString());
                    m.put("request", object.getString("request"));
                    m.put("request_type", object.getString("request_type"));
                    m.put("platform", object.getString("platform"));
                    m.put("cdk", etcOrder.getPayNo());
                    m.put("equipment_code", etcOrder.getBody());
                    m.put("obu_code",ctx.getObuId());
                    m.put("class", object.getString("class"));
                    m.put("method", object.getString("method"));
                    String s = PayUtil.generateSign(m, object.getString("secreKey"));
                    m.put("sign", s.substring(8, 24).toUpperCase());
                    String r = HttpUtils.doPost(object.getString("url"), m);
                    if (!StringUtils.isEmpty(r)) {
                        JSONObject jsonObject = JSON.parseObject(r);
                        log.info(jsonObject.toJSONString());
                    }
                //}
            } else {
                if (ctx.getChannel() != null && ctx.getChannel().equalsIgnoreCase(thirdCustomId)) {
                    try {
                        //同步消息给第三方充值系统
                        Map<String, String> m = new HashMap<>();
                        m.put("request", "public.handle.cdk_activation");
                        m.put("request_type", "request");
                        m.put("platform", "wxxcx");
                        m.put("cdk", ctx.getTransNo());
                        m.put("equipment_code", etcOrder.getBody());
                        m.put("class", "handle");
                        m.put("method", "cdk_activation");
                        String s = PayUtil.generateSign(m, "asfdaijfgpagpoas");
                        m.put("sign", s.substring(8, 24).toUpperCase());
                        String r = HttpUtils.doPost("https://klqqb.ganjiayou.com/etc/api/wxxcx/", m);
                        if (!StringUtils.isEmpty(r)) {
                            JSONObject jsonObject = JSON.parseObject(r);
                            log.info(jsonObject.toJSONString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("同步消息给第三方充值系统出现异常:{}", JSON.toJSONString(etcOrder));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("同步消息给第三方充值系统出现异常:{}", JSON.toJSONString(etcOrder));
        }

        //记录激活数据到ERP
        Date now = new Date();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("deleteFlag", "0");
        queryMap.put("obuDeviceSn", obuId);
        List<EtcDevice> list = etcOrderMapper.queryObjects(queryMap);
        if (!CollectionUtils.isEmpty(list) && list.size() == 1) {
            EtcDevice etcDevice = list.get(0);
            etcDevice.setActiveStatus(1);
            etcDevice.setActiveTime(now);
            etcOrderMapper.updateObject(etcDevice);
            //判断订单中的设备编号是否为空，是的话则进行数据回填,否则不处理
            if (etcDevice.getActiveStatus() != 1 && etcOrder != null && StringUtils.isEmpty(etcOrder.getBody()) && !StringUtils.isEmpty(etcDevice.getProductSn())) {
                etcOrder.setBody(etcDevice.getProductSn());
                mingchuangOrderMapper.updateById(etcOrder);
            }

            EtcObu obu = new EtcObu(null, obuId, 0, etcDevice.getIssuerName(), etcDevice.getObuModel(), activeState,
                    ctx.getEtcCardNo(), ctx.getCarId(), applyInfo.getId(), applyInfo.getOwnerType(), activeState,
                    ctx.getBeginDate(), ctx.getEndDate(), ctx.getBeginTime(), ctx.getEndTime(), etcOrder.getProvince(), etcOrder.getCity(),
                    etcOrder.getRegion(), etcOrder.getAddress(), now, now, etcOrder.getAmount());
            try {
                mingChuangEtcObuMapper.insert(obu);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void activeComplete(String obuId, String userId) {
        QueryWrapper<CurrentContext> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.gt("state", 0);
        qw.eq("delete_flag", 0);
        CurrentContext ctx = currentContextMapper.selectOne(qw);

        ApplyInfo applyInfo = applyInfoMapper.selectById(ctx.getApplyId());

        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo", ctx.getOrderNo());
        EtcOrder etcOrder = mingchuangOrderMapper.selectOne(wrapper);

        Integer activeState = 1;
        applyInfo.setState(2); //更改申请的状态为设备已激活
        applyInfoMapper.updateById(applyInfo);

        //删除当前进行时-逻辑删除
        ctx.setDeleteFlag(1);
        currentContextMapper.updateById(ctx);
        //currentContextMapper.deleteById(ctx.getId());

        //记录激活数据到ERP
        Date now = new Date();
        EtcObu obu = new EtcObu(null, obuId, 0, "铭创", "MC-OBU-01", activeState,
                ctx.getEtcCardNo(), ctx.getCarId(), applyInfo.getId(), applyInfo.getOwnerType(), activeState,
                ctx.getBeginDate(), ctx.getEndDate(), ctx.getBeginTime(), ctx.getEndTime(), etcOrder.getProvince(), etcOrder.getCity(),
                etcOrder.getRegion(), etcOrder.getAddress(), now, now, etcOrder.getAmount());
        try {
            mingChuangEtcObuMapper.insert(obu);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //更新库存状态
        EtcDealerObu etcDealerObu = new EtcDealerObu(null, obuId, now, activeState);
        UpdateWrapper<EtcDealerObu> uw = new UpdateWrapper<>();
        uw.eq("OBU_ID", obuId);
        etcDealerObuMapper.update(etcDealerObu, uw);

        //记录激活数据到ERP
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("deleteFlag", "0");
        queryMap.put("obuDeviceSn", obuId);
        List<EtcDevice> list = etcOrderMapper.queryObjects(queryMap);
        if (!CollectionUtils.isEmpty(list) && list.size() == 1) {
            EtcDevice etcDevice = list.get(0);
            etcDevice.setActiveStatus(1);
            etcDevice.setActiveTime(new Date());
            etcOrderMapper.updateObject(etcDevice);
        }
    }

    @Override
    public List<EtcObu> queryObjects(QueryWrapper<EtcObu> wrapper) {
        return mingChuangEtcObuMapper.selectList(wrapper);
    }

    @Override
    public int save(EtcObu obu) {
        return mingChuangEtcObuMapper.insert(obu);
    }

}
